#!/usr/bin/python
# -*- coding: utf-8 -*-

from os import access, mkdir, chmod, F_OK, R_OK
from shutil import copy
from mc102html import document, div, h1, h2, h3, h4, p, link, \
     text, table, tr, th, td, ul, li, span
import math

def M(id, score_list):
    return -1.0

CT = 0
AVG = 1
MAX = 2
MIN = 3
STD = 4
NUMBER = 0
TEXT = 1

class scores:

    def __init__(self):
    
        self.TERM="none"
        self.GROUPS_NAME = "none"
        self.DISCIPLINE_CODE = "MC999"
        self.DISCIPLINE_NAME = "Disciplina Inválida"
        self.SCORED_TESTS = []
        self.TESTS = []
	self.HIDDEN_TESTS = []
        self.GROUPS=[]
        self.BASEDIR=".."
        self.GROUPDIR="alunos"
        self.TESTSDIR="notas"
        self.HTMLDIR="html"
        self.AVERAGEFUNCTION=M
        self.ABSENT_TEXT = "Ausente"
        self.TEST_NOT_SCORED_TEXT = "Teste não corrigido"
        self.LABELS = {}
        self.MODE = 0
        self.Students = {}
        self.STATSTEXT = ""
        self.STATS = []
	self.AVERAGETYPES = [("FINAL", "Média Final")]
	self.TABLE = False
	self.TABLETEXT = ""

    def log(self,s):
        print "Aviso: %s" % (s)

    def model(self):
        # Cria a página
        page = document("MC102 - Algoritmos e programação de computadores","../",
                        div ("titulo",
                             h1("%s - %s" % (self.DISCIPLINE_CODE,
                                             self.DISCIPLINE_NAME)),
                             h4("%s, Turmas %s" % (self.TERM,
                                                   self.GROUPS_NAME)),
                             p(link("http://www.ic.unicamp.br", text("Instituto de computação")),
                               text(" - "),
                               link("http://www.unicamp.br", text("UNICAMP"))
                               )
                             )    
                        )
        return page

    def generate_scores(self):

        stats = {}
        
        if not access("%s/scores" % (self.HTMLDIR), F_OK):
            mkdir("%s/scores" % (self.HTMLDIR), self.MODE)

        TESTS = self.TESTS

        for gr in self.GROUPS:
            namearq = "%s/%s/Turma%s.alunos" % (self.BASEDIR,self.GROUPSDIR,gr)
            if (access(namearq, F_OK or R_OK)):
                arq = open(namearq)
                for al in arq.xreadlines():
                    fdata = al.split(":")
                    self.Students[int(fdata[0])] = [gr, int(fdata[0]), fdata[1], {}, 0.0]
                    for i in TESTS + self.HIDDEN_TESTS:
                        self.Students[int(fdata[0])][3][i] = {}
                        self.Students[int(fdata[0])][3][i]["PRESENT"] = False
                        self.Students[int(fdata[0])][3][i]["SCORE"] = 0.0
                        self.Students[int(fdata[0])][3][i]["COMMENT"] = ""
                
            else:
                self.log("Arquivo da Turma %s não encontrado" % (gr))

        for ts in self.SCORED_TESTS:
            stats[ts] = [0,0.0,0.0,10.0,0.0]
            namearq = "%s/%s/%s.notas" % (self.BASEDIR,self.TESTSDIR,ts)
            if (access(namearq, F_OK or R_OK)):
                arq = open(namearq)
                for nt in arq.xreadlines():
                    fdata = nt.split(":")
                    if int(fdata[0]) in self.Students:
                        stats[ts][CT] = stats[ts][CT] + 1
                        score = eval(fdata[1])
                        stats[ts][AVG] = stats[ts][AVG] + score
                        stats[ts][STD] = stats[ts][STD] + score * score
                        stats[ts][MAX] = max(stats[ts][MAX], score)
                        stats[ts][MIN] = min(stats[ts][MIN], score)
                        self.Students[int(fdata[0])][3][ts]["PRESENT"] = True
                        self.Students[int(fdata[0])][3][ts]["SCORE"] = score
                        if (len(fdata) == 3):
                            self.Students[int(fdata[0])][3][ts]["COMMENT"] = fdata[2]
                    else:
                        self.log("Aluno %s não encontrado (arquivo %s)" % (int(fdata[0]), ts))
                stats[ts][AVG] = stats[ts][AVG] / stats[ts][CT]
                stats[ts][STD] = (stats[ts][STD] / stats[ts][CT]) - (stats[ts][AVG] * stats[ts][AVG]) 
                stats[ts][STD] = math.sqrt(stats[ts][STD])
                

            else:
                self.log("Arquivo da atividade %s não encontrado" % (ts))

        students_list = self.Students.values()
        students_list.sort()

        main_dv = div ("conteudo", h2("Notas"))
		
        if (len(self.STATS) != 0):
            main_dv.add(p(link("stats.html", text(self.STATSTEXT))))

        if (self.TABLE):
            main_dv.add(p(link("table.html", text(self.TABLETEXT))))
	    table_dv = div ("conteudo", h2("Tabela"))
	    table_gr = None

        last_group = ""
        gr = None
	
        for item in students_list:
        
            if last_group != item[0]:
                last_group = item[0]
                if gr != None:
                    main_dv.add(gr)
		    if self.TABLE:
                    	table_dv.add(table_gr)

                main_dv.add(h3("Turma %s" % last_group))            
                gr = ul()
		if self.TABLE:
		    table_dv.add(h3("Turma %s" % last_group))
                    table_gr = table("class=\"notas\"")
	            table_line = tr(th("class=\"linha0\"",text("Nome")))
		    for i in TESTS:
			table_line.add(th("class=\"linha0\"", 
					text(self.LABELS[i])))
		    for i in self.AVERAGETYPES:
			table_line.add(th("class=\"linha0\"", 
					text(i[1])))
		    table_gr.add(table_line)
                    table_counter = 0
		

            #Adicionando o aluno no arquivo principal
            gr.add(li(link("%06d.html" % (item[1]), text("%06d - %s" % (item[1], item[2])))))
	    if self.TABLE:
		table_counter = (table_counter + 1) % 2
		table_line = tr(td("class=\"linha%d\"" % table_counter, 
			           text("%06d - %s" % (item[1], item[2]))))
		
            item[4] = self.AVERAGEFUNCTION(int(item[1]), item[3])

            page = self.model()
    
            # Cria o corpo da pagina
            dv = div ("conteudo", h2("Relatório de notas de %s" % (item[2])),
                      h3("RA: %06d - Turma %s" % (item[1], item[0])))

            #cria a table com as notas
            tbl = table("class=\"notas\"", tr(th("align=\"left\"", text("Atividade")),
                                              th("align=\"right\"", text("Nota")),
                                              th("align=\"left\"", text("Comentário"))))

            line_id = 1
            
            for i in TESTS:
 
                line = tr(td("class=\"linha%d\"" % line_id, text("%s" % self.LABELS[i])))
                
                if (i not in self.SCORED_TESTS):
                    line.add(td("class=\"linha%ddr\"" % line_id, text("%s" % self.TEST_NOT_SCORED_TEXT)))
		    if self.TABLE:
                        table_line.add(td("class=\"linha%ddr\"" % table_counter, text("%s" % self.TEST_NOT_SCORED_TEXT)))

                elif not item[3][i]["PRESENT"]:
                    line.add(td("class=\"linha%ddr\"" % line_id, text("%s" % self.ABSENT_TEXT)))
		    if self.TABLE:
                        table_line.add(td("class=\"linha%ddr\"" % table_counter, text("%s" % self.ABSENT_TEXT)))			
                else:
                    line.add(td("class=\"linha%ddr\"" % line_id, text("%.2f" % (item[3][i]["SCORE"]))))
		    if self.TABLE:
                        table_line.add(td("class=\"linha%ddr\"" % table_counter, text("%.2f" % (item[3][i]["SCORE"]))))			

                line.add(td("class=\"linha%d\"" % line_id, text("%s" % item[3][i]["COMMENT"] )))

                line_id = (line_id + 1) % 2
                
                tbl.add(line)

	    dv.add (tbl)	    
	    for avg in self.AVERAGETYPES:
	        if avg[2] == NUMBER:
   		    dv.add(p(span("medias", (text("%s: %.2f" % 
			(avg[1], item[4][avg[0]]))))))
		elif avg[2] == TEXT:
   		    dv.add(p(span("medias", (text("%s: %s" % 
			(avg[1], item[4][avg[0]]))))))
		if self.TABLE:
		    if avg[2] == NUMBER:		    	
                        table_line.add (td("class=\"linha%d\"" % 
				table_counter, 
				text("%.2f" % (item[4][avg[0]]))))
		    elif avg[2] == TEXT:
                        table_line.add (td("class=\"linha%d\"" % 
				table_counter, 
				text("%s" % (item[4][avg[0]]))))


	    if self.TABLE:
		table_gr.add(table_line)

            page.add(dv)

            arq = open("%s/scores/%06d.html" % (self.HTMLDIR, item[1]), "w")
            arq.write(page.tohtml())
            arq.close()
            chmod("%s/scores/%06d.html" % (self.HTMLDIR, item[1]), self.MODE)

        if gr != None:
            main_dv.add(gr)
	if self.TABLE and table_gr != None:
           table_dv.add(table_gr)
        main_page = self.model()
        main_page.add(main_dv)

        arq = open("%s/scores/index.html" % (self.HTMLDIR), "w")
        arq.write(main_page.tohtml())
        arq.close()
        chmod("%s/scores/index.html" % (self.HTMLDIR), self.MODE)

        # Escrevendo página de estatísticas
        if len(self.STATS) != 0:
            main_page = self.model()
            main_dv = div ("conteudo", h2("Estatísticas"))

            tests = ul ()
            
            for i in self.SCORED_TESTS:
		if i not in self.HIDDEN_TESTS:
                    this_test = ul()
                    this_test.add(li(text("Número de alunos que " \
			 "realizaram a tarefa: %02d" % (stats[i][CT]))))
                    if AVG in self.STATS:
                        this_test.add(li(text("Média: %.2f" % 
					(stats[i][AVG]))))
                    if STD in self.STATS:
                        this_test.add(li(text("Desvio Padrão: %.2f" % 
				(stats[i][STD]))))
                    if MAX in self.STATS:
                        this_test.add(li(text("Máximo: %.2f" % 
				(stats[i][MAX]))))
                    if MIN in self.STATS:
                        this_test.add(li(text("Mínimo: %.2f" % 
				(stats[i][MIN]))))  
                    tests.add (li(span("stats", text(self.LABELS[i])), 
				  this_test))
                
            main_dv.add(tests)
            main_page.add(main_dv)

            arq = open("%s/scores/stats.html" % (self.HTMLDIR), "w")
            arq.write(main_page.tohtml())
            arq.close()
            chmod("%s/scores/stats.html" % (self.HTMLDIR), self.MODE)

	if self.TABLE:
	   
            main_page = self.model()
            main_dv = div ("conteudo", h2("Tabela de notas"))

            main_dv.add(table_dv)
            main_page.add(main_dv)

            arq = open("%s/scores/table.html" % (self.HTMLDIR), "w")
            arq.write(main_page.tohtml())
            arq.close()
            chmod("%s/scores/table.html" % (self.HTMLDIR), self.MODE)
		
